import {Injectable} from '@angular/core';

@Injectable()
export class LSService {

    constructor() {

    }

    set(key, value) {
        if (!(window.localStorage && window.localStorage instanceof Storage) ) {
            console.log('不支持 localstorage 啊 set ------');
            return;
        }

        let x = JSON.stringify(value);
        if (value) {
            localStorage.setItem(key, x);
        }
    }

    get(key) {
        //if (!(window.Storage && window.localStorage && window.localStorage instanceof Storage) ) {
        if (!(window.localStorage && window.localStorage instanceof Storage) ) {
            console.log('不支持 localstorage啊 get ------');
            return null;
        }

        var defaultValue = "";
        var stored = localStorage.getItem(key);

        if (defaultValue && stored === null) {
            stored = defaultValue;
        }

        let x = JSON.parse(stored);
        console.dir(x);

        return x;
    }

    update(key, value) {
        if (value) {
            localStorage.setItem(key, JSON.stringify(value));
        }
    }

    //删除单个 key
    remove(key) {
        localStorage.removeItem(key);
    }


    clear() {
        localStorage.clear();
    }
}
